﻿using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace RegexSharp.Helper
{
    public class Serializer<T>
    {
        public void Serialize(T obj, string filePath)
        {
            using (StreamWriter sw = new StreamWriter(filePath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(sw, obj);
            }
        }

        public bool CanDeserialize(string filePath)
        {
            bool canDeserialize;

            if (File.Exists(filePath))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));

                using (StreamReader sr = new StreamReader(filePath))
                using (XmlReader xr = XmlReader.Create(sr))
                {
                    canDeserialize = serializer.CanDeserialize(xr);
                }
            }
            else
            {
                canDeserialize = false;
            }

            return canDeserialize;
        }

        public T Deserialize(string filePath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T obj;

            using (StreamReader sr = new StreamReader(filePath))
            {
                obj = (T)serializer.Deserialize(sr);
            }

            return obj;
        }
    }
}
